package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();
        while(!begin.equals(end.plusDays(1))) {
            // 将每天日期加入dataList
            dateList.add(begin);
            // 查询当天已完成订单金额总数 ，加入turnoverList
            LocalDateTime dayBeginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime dayEndTime = LocalDateTime.of(begin, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", dayBeginTime);
            map.put("endTime", dayEndTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getAmountSum(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
            // 进入下一天
            begin = begin.plusDays(1);
        }
        String stringDataList = StringUtils.join(dateList, ",");
        String stringTurnoverList = StringUtils.join(turnoverList, ",");
        return TurnoverReportVO.builder()
                .dateList(stringDataList)
                .turnoverList(stringTurnoverList)
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        while(!begin.equals(end.plusDays(1))) {
            // 将每天日期加入dataList
            dateList.add(begin);
            // 查询当天及之前所有加入的User数量
            LocalDateTime dayBeginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime dayEndTime = LocalDateTime.of(begin, LocalTime.MAX);
            Map map = new HashMap();
            map.put("endTime", dayEndTime);
            Integer totalNum = userMapper.getUserCount(map);
            totalUserList.add(totalNum);
            // 查询当天新增用户数量
            map.put("beginTime", dayBeginTime);
            Integer newNum = userMapper.getUserCount(map);
            newUserList.add(newNum);
            // 进入下一天
            begin = begin.plusDays(1);
        }
        String stringDataList = StringUtils.join(dateList, ",");
        String stringTotalUserList = StringUtils.join(totalUserList, ",");
        String stringNewUserList = StringUtils.join(newUserList, ",");
        return UserReportVO.builder()
                .dateList(stringDataList)
                .totalUserList(stringTotalUserList)
                .newUserList(stringNewUserList)
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        // // 获取时间段内总订单, 有效订单数，完成率，笨比写法
        // LocalDateTime totalBeginTime = LocalDateTime.of(begin, LocalTime.MIN);
        // LocalDateTime totalEndTime = LocalDateTime.of(end, LocalTime.MAX);
        // List<Integer> totalOrderCounts = getOrderCounts(totalBeginTime, totalEndTime);
        // Double orderCompletionRate = totalOrderCounts.get(0) == 0 ? 0 : Double.parseDouble(totalOrderCounts.get(1).toString()) / totalOrderCounts.get(0);
        // 获取订单列表
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        while(!begin.equals(end.plusDays(1))) {
            // 将每天日期加入dataList
            dateList.add(begin);
            // 查询当天及之前所有加入的User数量
            LocalDateTime dayBeginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime dayEndTime = LocalDateTime.of(begin, LocalTime.MAX);
            List<Integer> dayOrderCounts = getOrderCounts(dayBeginTime, dayEndTime);
            orderCountList.add(dayOrderCounts.get(0));
            validOrderCountList.add(dayOrderCounts.get(1));
            // 进入下一天
            begin = begin.plusDays(1);
        }
        // 获取时间段内总订单, 有效订单数，完成率
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ','))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ','))
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        // 设置时间区间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTop10Number(beginTime, endTime);
        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1. 查询数据库，获取营业数据，查询最近30天的运营数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        // 2. 通过POI将数据写入到Excel文件中
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            // 3. 通过数据流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 获取一段时间内的totalOrderCount和validOrderCount,第0个元素为totalOrderCount，第1个元素为validOrderCount
     * @param beginTime
     * @param endTime
     * @return
     */
    private List<Integer> getOrderCounts(LocalDateTime beginTime, LocalDateTime endTime) {
        List<Integer> list = new ArrayList<>();
        Map totalMap = new HashMap<>();
        totalMap.put("beginTime", beginTime);
        totalMap.put("endTime", endTime);
        Integer totalOrderCount = orderMapper.getOrderCount(totalMap);
        totalOrderCount = totalOrderCount == null ? 0 : totalOrderCount;
        totalMap.put("status", Orders.COMPLETED);
        Integer validOrderCount = orderMapper.getOrderCount(totalMap);
        validOrderCount = validOrderCount == null ? 0 : validOrderCount;
        list.add(totalOrderCount);
        list.add(validOrderCount);
        return list;
    }
}
